package com.xiaobaibai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobaibai.common.OrderCommon;
import com.xiaobaibai.common.OrderEnum;
import com.xiaobaibai.dao.ProductEvaluationDao;
import com.xiaobaibai.entity.*;
import com.xiaobaibai.service.*;
import com.xiaobaibai.units.SecurityUnit;
import com.xiaobaibai.units.ValidList;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaobaibai
 * @since 2020-10-27
 */
@Service
public class ProductEvaluationServiceImpl extends ServiceImpl<ProductEvaluationDao, ProductEvaluation> implements IProductEvaluationService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IOrderItemService orderItemService;

    @Autowired
    private IProductEvaluationService productEvaluationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    @Cacheable(value = {"evaluation"},key = "#root.methodName+'-'+#productId")
    public List<ProductEvaluation> getTwoProductEvaluation(Integer productId) {
        return this.baseMapper.getTwoProductEvaluation(productId);
    }

    @Override
    @Cacheable(value = {"evaluation"},key = "#root.methodName+'-'+#productId")
    public List<ProductEvaluation> getListByProductId(Integer productId) {
        QueryWrapper<ProductEvaluation> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("product_id",productId);
        return this.list(queryWrapper);
    }

    @Override
    public void addEvaluationList(ValidList<ProductEvaluation> list) {
        //只用检验第一个元素是否符合校验即可
        ProductEvaluation productEvaluation = list.get(0);
        String orderItemId = productEvaluation.getOrderItemId();
        if(orderItemId==null)
            throw new RuntimeException("请指定订单itemId");
        QueryWrapper<OrderItem> q1=new QueryWrapper<>();
        q1.select("product_id","order_id");
        q1.eq("id",orderItemId);
        OrderItem orderItem = orderItemService.getOne(q1);
        if(orderItem==null)
            throw new RuntimeException("请输入正确的itemId");
        if(!productEvaluation.getProductId().equals(orderItem.getProductId())){
            throw new RuntimeException("请评价对应的商品");
        }
        Integer userId = SecurityUnit.getUserId();
        QueryWrapper<Order> q2=new QueryWrapper<>();
        q2.select("user_id","order_id","order_status");
        q2.eq("order_id",orderItem.getOrderId());
        Order order = orderService.getOne(q2);
        if(!order.getUserId().equals(userId))
            throw new RuntimeException("购买后方可评价此商品");
        if(!order.getOrderStatus().equals(OrderEnum.OK.getCode()))
            throw new RuntimeException("非已完成状态,禁止评价");

        QueryWrapper<User> q3=new QueryWrapper<>();
        q3.select("user_name","user_image");
        q3.eq("user_id",userId);
        User user = userService.getOne(q3);

        List<ProductEvaluation> productEvaluationList=new ArrayList<>(list.size());
        List<String> keyList=new ArrayList<>(list.size());
        list.forEach(l->{
            Integer productId = l.getProductId();
            Product product = productService.getProductById(productId);
            l.setUserId(userId);
            l.setProductName(product.getProductName());
            l.setUserName(user.getUserName());
            l.setUserImage(user.getUserImage());
            if(StringUtils.isBlank(l.getEvaluationContent()))
                l.setEvaluationContent("默认好评!");
            productEvaluationList.add(l);
            keyList.add("cache:getListByProductId-"+productId);
        });
        productEvaluationService.saveBatch(productEvaluationList);

        stringRedisTemplate.delete(keyList);
        Boolean flag = stringRedisTemplate.hasKey(OrderCommon.waitEvaluationOrder + userId);
        //减去redis里中的未评价orderId
        if(flag)//清除一个待评价订单
            stringRedisTemplate.opsForList().remove(OrderCommon.waitEvaluationOrder+userId,1,order.getOrderId());

    }

    @Override
    public void defaultEvaluation(String orderId) {
        QueryWrapper<Order> q1=new QueryWrapper<>();
        q1.select("order_id","user_id","order_status");
        q1.eq("order_id",orderId);
        Order order = orderService.getOne(q1);
        //默认评价:如果非完成状态就不用帮忙评价了
        if(!order.getOrderStatus().equals(OrderEnum.OK.getCode()))
            throw new RuntimeException("非已完成状态,停止自动评价流程");
        QueryWrapper<User> q2=new QueryWrapper<>();
        q2.select("user_id","user_name","user_image");
        q2.eq("user_id",order.getUserId());
        User user = userService.getOne(q2);

        QueryWrapper<OrderItem> q3=new QueryWrapper<>();
        q3.select("product_id");
        q3.eq("order_id",orderId);
        List<OrderItem> orderItemList = orderItemService.list(q3);

        List<ProductEvaluation> productEvaluationList=new ArrayList<>(orderItemList.size());
        orderItemList.forEach(l->{
            Integer productId = l.getProductId();
            Product product = productService.getProductById(productId);
            ProductEvaluation productEvaluation=new ProductEvaluation();
            productEvaluation.setProductId(productId);
            productEvaluation.setProductName(product.getProductName());
            productEvaluation.setUserImage(user.getUserImage());
            productEvaluation.setUserName(user.getUserName());
            productEvaluation.setUserId(user.getUserId());
            productEvaluation.setEvaluationLevel(2);
            productEvaluation.setEvaluationContent("默认好评!");
            productEvaluationList.add(productEvaluation);
        });
        productEvaluationService.saveBatch(productEvaluationList);
        Boolean flag = stringRedisTemplate.hasKey(OrderCommon.waitEvaluationOrder + user.getUserId());
        //减去redis里中的未评价orderId
        if(flag)//清除一个待评价订单
            stringRedisTemplate.opsForList().remove(OrderCommon.waitEvaluationOrder+user.getUserId(),1,order.getOrderId());
    }


}
